package com.catfish.common.util;


import cn.hutool.core.util.StrUtil;
import org.ho.yaml.Yaml;
import sun.awt.OSInfo;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.HashMap;
import java.util.Map;

/**
 * yml工具
 *
 * @author luojm
 * 2021/12/3 16:27
 */
public class YmlUtils {

    private static final String BOOTSTRAP_FILE = "bootstrap.yml";
    public static final String CLASSPATH;
    static {
        if(OSInfo.OSType.WINDOWS.equals(OSInfo.getOSType())){
            CLASSPATH = ClassLoader.getSystemResource("").getPath().substring(1);
        }else {
            CLASSPATH = ClassLoader.getSystemResource("").getPath();
        }
        System.err.println(CLASSPATH);
    }


    /**
     * 根据文件名获取yml的文件内容
     */
    @SuppressWarnings("unchecked")
    public static Map<String, String> getYmlByFileName(String file) {
        Map<String, String> result = new HashMap<>(16);
        if (file == null) {
            file = BOOTSTRAP_FILE;
        }
        try {
            Map<String, Object> param = (Map<String, Object>) Yaml.load(new File(CLASSPATH + file));
            for (Map.Entry<String, Object> entry : param.entrySet()) {
                String key = entry.getKey();
                Object val = entry.getValue();

                if (val instanceof Map) {
                    result.putAll(forEachYaml(key, (Map<String, Object>) val));
                } else {
                    result.put(key, val.toString());
                }
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 根据key获取值
     */
    public static String getStrValue(String key) {
        Map<String, String> map = getYmlByFileName(null);
        if (map.isEmpty()) {
            return null;
        }
        return map.get(key);
    }

    /**
     * 根据key获取值
     */
    public static Integer getIntValue(String key) {
        Map<String, String> map = getYmlByFileName(null);
        if (map.isEmpty()) {
            return 0;
        }
        try {
            return Integer.parseInt(map.get(key));
        } catch (Exception e) {
            return 0;
        }
    }

    /**
     * 遍历yml文件，获取map集合
     */
    @SuppressWarnings("all")
    public static Map<String, String> forEachYaml(String keyStr, Map<String, Object> obj) {
        Map<String, String> result = new HashMap<>(16);
        for (Map.Entry<String, Object> entry : obj.entrySet()) {
            String key = entry.getKey();
            Object val = entry.getValue();
            String strNew = "";
            if (StrUtil.isNotBlank(keyStr)) {
                strNew = keyStr + "." + key;
            } else {
                strNew = key;
            }
            if (val instanceof Map) {
                forEachYaml(strNew, (Map<String, Object>) val);
            } else {
                result.put(strNew, val.toString());
            }
        }
        return result;
    }
}
